package com.hbgc.controller;

import com.hbgc.entity.User;
import com.hbgc.ocnstant.Constants;
import com.hbgc.service.UserService;
import com.hbgc.utils.EncryptionUtils;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/front/login")
public class UserLoginController {
    @Autowired
    private UserService iUserService;
    @ResponseBody
    @RequestMapping("login")
    public  Map<String,String> login(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        String autoLogin = request.getParameter("autoLogin");
        Map<String,String>map = new HashMap<>();
        //根据用户名查询
        User userByName = iUserService.getUserByName(user);
        System.out.println(userByName);
        //匹配用户名
        if (userByName==null) {
             map.put("message","用户名不存在");
            }
        //匹配密码
        else if (!userByName.getPassword().equals(EncryptionUtils.encryptMD5(user.getPassword()))) {
            map.put("message","密码不正确");
           }
       else {
            request.getSession().setAttribute(Constants.USER_SESSION_CODE, userByName);
            System.out.println("----------------------------------------------------------");
            System.out.println(request.getSession().getAttribute(Constants.USER_SESSION_CODE));
            map.put("message", "登录成功");
            map.put("result", "200");
            //添加cookie
            Cookie cUserName = new Cookie("username", user.getUsername());
            Cookie cPassword = new Cookie("password", user.getPassword());

            if (!StringUtils.isNullOrEmpty(autoLogin)) {
                cUserName.setMaxAge(60 * 60 * 24 * 7);
                cPassword.setMaxAge(60 * 60 * 27 * 7);
            } else {
                cUserName.setMaxAge(0);
                cPassword.setMaxAge(0);
            }
            cUserName.setPath(request.getContextPath());
            cPassword.setPath(request.getContextPath());
            response.addCookie(cUserName);
            response.addCookie(cPassword);
        }
        return map;
    }

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping("tologin")
    public String tologin(){
        return "front/login";
    }

}
